<template>
  <a-drawer
    :visible="formVisible"
    :width="500"
    unmount-on-close
    :title="isEdit ? '编辑' : '新增'"
    @ok="submit"
    @cancel="close"
  >
    <div>
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col-props="{ span: 8 }"
        :wrapper-col-props="{ span: 16 }"
      >
        <a-form-item field="roleName" label="角色名称">
          <a-input v-model="form.roleName" placeholder="请填写角色名称" />
        </a-form-item>
        <a-form-item field="roleCode" label="角色编码">
          <a-input v-model="form.roleCode" placeholder="请填写角色编码" />
        </a-form-item>
        <a-form-item field="roleDesc" label="角色描述">
          <a-input v-model="form.roleDesc" placeholder="请填写角色描述" />
        </a-form-item>
        <a-form-item field="dsType" label="数据权限">
          <a-select
            v-model="form.dsType"
            :options="DATA_SCOPES"
            placeholder="请选择数据权限"
          ></a-select>
        </a-form-item>
        <a-form-item v-if="form.dsType === DataScope.CUSTOM">
          <a-tree-select
            v-model="dsScope"
            :field-names="{
              key: 'id',
              title: 'name',
              children: 'children',
            }"
            :multiple="true"
            :allow-clear="true"
            :data="treeData"
            placeholder="请选择组织机构"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { FieldRule, Message } from '@arco-design/web-vue';
  import { ref, watch, computed } from 'vue';
  import { addRole, updateRole, DATA_SCOPES, DataScope } from '@/api/upms/role';
  import { useVisible } from '@/hooks/visible';
  import { useRequest } from 'vue-request';
  import { getOrgTree } from '@/api/upms/org';

  const formRef = ref();

  const rules: Record<string, FieldRule[]> = {
    roleName: [
      {
        type: 'string',
        required: true,
        message: '角色名不能为空',
      },
    ],
    roleCode: [
      {
        type: 'string',
        required: true,
        message: '角色编码不能为空',
      },
    ],
    dsType: [
      {
        type: 'string',
        required: true,
        message: '数据权限不能为空',
      },
    ],
  };

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const emit = defineEmits<{
    (e: 'update:visible', v: boolean): void;
    (e: 'refresh'): void;
  }>();

  const { formVisible, close } = useVisible(props, emit);

  const form = ref(props.formData);

  const { data: treeData } = useRequest(getOrgTree);

  // 判断是编辑还是新增
  const isEdit = computed(() => !!form.value.id);

  /**
   * 拼接自定义权限范围
   */
  const dsScope = computed({
    get() {
      // 主键类型改为数字了
      return form.value.dsScope?.split(',').map((v: any) => String(v)) ?? [];
    },
    set(v: number[]) {
      form.value.dsScope = v.length > 0 ? v.join(',') : undefined;
    },
  });

  const submit = async () => {
    formVisible.value = true;
    const validate = await formRef.value.validate();
    if (!validate) {
      if (isEdit.value) {
        await updateRole(form.value).then(() => {
          Message.success('修改成功');
        });
      } else {
        await addRole(form.value).then(() => {
          Message.success('添加成功');
        });
      }
      formVisible.value = false;
      emit('refresh');
    }
  };

  watch(
    () => props.formData,
    (val) => {
      form.value = val;
    }
  );
</script>
